/**
 * Created by walkman on 2017/7/1.
 */
/*var timer;

 //提交注册
 $(function () {

 // 注册按钮
 $('#btnRegister').bind('click', registerUser);

 function registerUser() {

 if ($("#password2").val() != "" && $.trim($("#password2").val()).length < 6 || $.trim($("#password2").val()).length > 20) {
 // errorTip();
 // $("#error_tip").html("密码请输入6-20个字符");
 return false;
 }
 ;
 // $("#username").val($.trim($("#ajax_phone").val()));
 var data = {
 'userCode': $.trim($("#username").val()),
 'userPassword': $.md5($.trim($("#password1").val())),
 'userConfirmPassword': $.md5($.trim($("#password2").val())),
 'verify': $.trim($("#verify").val()),
 'refer': $.trim($("#refer").val()),
 'terminalType': 3
 // 'verifyCode': $('#ajax_phone_code').val(),
 // 'channelCode': 'shake'
 };
 $.ajax({
 async: false,
 type: 'post',
 url: "/user/registerAndloginUser",
 dataType: 'json',
 data: data,
 success: function (result) {
 if (result.retCode == '1') {
 // success(data.msg, function () {
 //   location.href = "/";
 // })
 location = "index.html";
 } else {
 // error(data.msg, function () {
 //   obj.bind('click', login)
 // });
 }
 }
 })
 }

 // function login() {
 //   var username = $('#username').val(),
 //     pwd = $('#pwd').val(),
 //     verify = $('#verify').val();
 //   var obj = $('#jax');
 //   obj.unbind('click');
 //   $.post("", {username: username, pwd: pwd, verify: verify}, function (data) {
 //     $('#codeImg').attr('src', "/captcha.html");
 //     if (data.code == 1) {
 //       success(data.msg, function () {
 //         location.href = "/";
 //       })
 //     } else {
 //       error(data.msg, function () {
 //         obj.bind('click', login)
 //       });
 //     }
 //   })
 // }
 });

 $(function () {

 // var ref = $.trim(WFB.tools.getQueryString("ref"));
 // if (!ref) {
 //   $('.ref_wrap').show()
 // }
 //
 // $('#ref').add($('#refe')).val(ref);
 // var $form = $("#userForm"),
 //   $form_E = $('#enterpriseForm');
 //
 // //图片验证码正确提示元素
 // var $code_state = $("#codeState");
 // $form[0].reset();

 //验证码
 var src = server + "/captcha/gen-vcode?",
 $valid_img = $("#code_img");
 $valid_img.attr("src", src);
 $valid_img.click(function () {
 $valid_img.attr("src", src + Math.random());
 $("#verify").val("");
 //$code_state.hide();
 });

 //回车转tab(按tabindex顺序)
 $("#registerForm input").on("keydown.enter_convert", function (e) {

 if (e.which == 13) {
 var tabindex = parseInt(this.getAttribute('tabindex')) + 1;
 if (tabindex > 2) {
 return true;
 }
 $("#registerForm input[tabindex='" + tabindex + "']").focus();
 return false;
 }
 });

 $("input[name=vcode]").keyup(function () {
 $.ajax({
 async: false,
 type: 'get',
 url: server + "/captcha/check-vcode?vcode=" + $(this).val(),
 dataType: 'json',
 success: function (data) {
 if (data.result) {
 //$('#sendVeryCode').removeAttr('disabled').removeClass('disable_btn');
 }
 }
 })
 });

 //
 /!*
 $('#sendVeryCode').click(function () {
 $("#mobilePhone").validate({
 rules: {
 mobilePhone: {
 required: true,
 mobileZH: true
 }
 },
 messages: {
 mobilePhone: {
 required: "请输入手机号",
 mobileZH: "手机号格式错误",
 remote: "手机号已注册"
 }
 },
 onkeyup: function (element, event) {
 if (event.which === 9 && this.elementValue(element) === "") {
 return;
 } else if (element.name in this.submitted || element === this.lastElement) {
 var is_error = this.element(element);
 }
 },
 wrapper: "div",
 errorElement: "div",
 errorPlacement: function (error, element) {
 element.parent().append(error.addClass("common_tips_left_red reg_tip").append('<span>&#9670;</span>'))
 },
 focusInvalid: false,
 focusCleanup: true
 })

 WFB.getData({
 ajaxSettings: {
 type: "post",
 url: server + "/web/vcodepc",
 data: {
 mobilePhone: $('#mobilePhone').val(),
 verifyCodeType: 1,
 vcode: $('#vcode').val()
 }
 },
 successCallback: function (res) {
 var $btn = $('#sendVeryCode'),
 seconds = 60;
 $btn.attr("disabled", true).addClass('disable_btn');

 timer = setInterval(function () {
 seconds--;
 $btn.html("重新发送 " + seconds);
 if (seconds < 1) {
 clearInterval(timer);
 $btn.html("获取验证码");
 $(".code_img").click();
 }
 }, 1000);
 },
 otherCodeCallback: function (res) {
 if (res.retCode != 1) {
 if (res.retMsg.indexOf('手机号') > -1) {
 if (!!$("#mobilePhone").parent().find('.reg_tip').html()) {
 $form.validate().element($("#mobilePhone"))
 } else {
 $('#mobilePhone').parent().append('<div class="common_tips_left_red reg_tip" style="display: block;"><div id="amount-error" class="error" style="display: block;">' + res.retMsg + '</div><span>◆</span></div>');
 }
 } else {
 $('.code_img').parent().append('<div class="common_tips_left_red reg_tip" style="display: block;"><div id="amount-error" class="error" style="display: block;">' + res.retMsg + '</div><span>◆</span></div>');
 $('#sendVeryCode').attr("disabled", true);
 $('#sendVeryCode').addClass('disable_btn');
 $(".code_img").click();
 }
 }
 }
 })
 })
 *!/
 //获取企业注册手机验证码
 /!*
 $('#sendVeryCode_e').click(function () {
 if (!$('#mobilePhone_e').val()) return;
 DYC.getData({
 ajaxSettings: {
 url: server + "/web/noauth",
 data: {
 method: "/user/getVerifyCode",
 mobilePhone: $('#mobilePhone_e').val(),
 verifyCodeType: 1,
 vcode: $('#vcode').val()
 }
 },
 successCallback: function (res) {
 var $btn = $('#sendVeryCode_e'),
 seconds = 60;
 $btn.attr("disabled", true);

 timer = setInterval(function () {
 seconds--;
 $btn.html("重新发送 " + seconds);
 if (seconds < 1) {
 clearInterval(timer);
 $btn.html("获取验证码").attr("disabled", false);
 }
 }, 1000);
 },
 otherCodeCallback: function (res) {
 if (res.retCode != 1) {
 $('#mobilePhone_e').parent().append('<div class="common_tips_left_red reg_tip" style="display: block;"><div id="amount-error" class="error" style="display: block;">' + res.retMsg + '</div><span>◆</span></div>')
 }
 }
 })
 })
 **!/
 //validate添加手机号码验证
 // $.validator.addMethod("mobileZH", function (value, element) {
 //   return this.optional(element) || WFB.check.isTel(value);
 // }, "请修正该字段");

 //password
 // $.validator.addMethod("password", function (value, element) {
 //   return this.optional(element) || WFB.check.isPwd(value);
 // }, "请修正该字段");

 /!*
 $form.validate({
 rules: {
 mobilePhone: {
 required: true,
 mobileZH: true
 },
 vcode: {
 required: true,
 rangelength: [4, 4],
 remote: {
 url: server + "/web/check-vcode",
 dataType: "json",
 dataFilter: function (data, type) {
 var state = data.result === true || data.result === "true";
 state ? ($('#sendVeryCode').removeAttr('disabled'), $('#sendVeryCode').removeClass('disable_btn')) : ($('#sendVeryCode').attr('disabled', 'disabled'), $('#sendVeryCode').addClass('disable_btn'));
 return state;
 }
 }
 },
 verifyCode: {
 required: true,
 rangelength: [6, 6],
 remote: {
 url: server + "/web/noauth",
 data: {
 method: '/user/checkVerifyCode',
 mobilePhone: function () {
 return $('.mobilePhone').val();
 },
 verifyCodeType: 1
 },
 dataType: "json",
 dataFilter: function (data, type) {
 var state = data.retCode === 1;
 return state;
 }
 }
 },
 password: {
 required: true,
 password: true,
 },
 inviteMobilePhone: {
 required: false,
 mobileZH: true,
 },
 Fruit: "required"
 },
 messages: {
 mobilePhone: {
 required: "请输入手机号",
 mobileZH: "手机号格式错误",
 remote: "该手机号码已被注册"
 },
 vcode: {
 required: "请输入4位图片验证码",
 rangelength: "图片验证码为4位",
 remote: "验证码错误"
 },
 verifyCode: {
 required: "请输入6位短信验证码",
 rangelength: "验证码为6位数字",
 remote: "验证码错误"
 },
 password: {
 required: "请输入密码",
 password: "密码格式错误"
 },
 inviteMobilePhone: {
 mobileZH: "手机号格式错误"
 },
 Fruit: "您还未接受服务协议"
 },
 onkeyup: function (element, event) {
 if (event.which === 9 && this.elementValue(element) === "") {
 return;
 } else if (element.name in this.submitted || element === this.lastElement) {
 var is_error = this.element(element);
 if (element.name == "vcode") {
 var $codeImg = $(".code_img").parent();
 !is_error ? $codeImg.find(".reg_tip").css("display", "inline-block") : $codeImg.find(".reg_tip").hide()
 }
 if (element.name == "validCode") {
 !is_error ? $code_state.css("display", "inline-block") : $code_state.hide()
 }
 }
 },
 submitHandler: function (form) {
 $(form).attr("action", server + "/flow/dispatch_post.do");
 //showModal();
 return true;
 },
 //onfocusout: false,
 wrapper: "div",
 errorElement: "div",
 errorPlacement: function (error, element) {
 //element.after(error.addClass("valid_tip").append('<span class="arrow"><span class="arrow_in"></span></span>'));
 element.parent().append(error.addClass("common_tips_left_red reg_tip").append('<span>&#9670;</span>'))
 },
 focusInvalid: false,
 focusCleanup: true
 });
 *!/
 });*/

/*******************************************************************************************************/
/**
 * Created by cj on 2017/7/16.
 */
// SetCookie('leftTime', null);
//邀请码
var invitationCode = '';
invitationCode = getQueryString('rec');
$('#invited').val(invitationCode).attr({'readonly': 'readonly'});
var invitationCodeCheck = true;
if (invitationCode == null || invitationCode == '' || typeof invitationCode == 'underfined') {
  $('input').attr({'readonly': 'readonly'});
  regErr('请联系推荐人获取邀请码链接!');
  invitationCodeCheck = false;
}
/*else{
 $.ajax({
 async: true,
 type: 'post',
 url: "/user/queryRef",
 dataType: 'json',
 data: {ref:invitationCode},
 success: function (json) {
 if (json.retCode == '1') {
 regHide();
 invitationCodeCheck = true;
 // $('#invited').val(json.data.userCode);
 $('#invited').val(invitationCode);
 } else {
 regErr('邀请码错误,请联系邀请人核对邀请码！');
 $('input').attr({'readonly':'readonly'});
 invitationCodeCheck = false;
 }
 }
 })
 }*/
//验证码
$valid_img = $("#code_img");
if (getCookie('leftTime') == 'null') {
  var lifttime = null;
} else {
  lifttime = getCookie('leftTime');
  liftTimeFn();
}
//验证码验证
var vCodeCheck = true;
$valid_img.click(function () {
  if (lifttime != null) {
    return;
  }
  var phone = $.trim($('.phone>input').val());
  if (phone == '') {
    regErr('手机号不能为空');
    return;
  } else if (!phone.match(reg.phone)) {
    regErr('手机号为11位阿拉伯数字');
    return;
  }
  $.ajax({
    type: 'post',
    url: "/user/sendMsg",
    data: {tel: $('#phoneNum').val()},
    dataType: 'json',
    success: function (json) {
      if (json.retCode == '1') {
        regHide();
        SetCookie('leftTime', 90);
        lifttime = getCookie('leftTime');
        liftTimeFn();
      } else {
        regErr(json.retMsg);
      }
    }
  });
});
function liftTimeFn() {
  if (lifttime >= 0) {
    var timer = setInterval(function () {
      lifttime--;
      SetCookie('leftTime', lifttime);
      $('#code_img').html(lifttime + '秒后重新发送');
      if (lifttime <= 0) {
        clearInterval(timer);
        timer = null;
        SetCookie('leftTime', null);
        lifttime = null;
        $('#code_img').html('获取验证码');
      }
    }, 1000);
  }
}

$("#verify_").keyup(function () {
  $.ajax({
    type: 'post',
    url: "/user/validMsg",
    data: {tel: $('#phoneNum').val(), msg: $('#verify_').val()},
    dataType: 'json',
    success: function (json) {
      if (json.retCode == '1') {
        regHide();
        vCodeCheck = true;
      } else {
        regErr(json.retMsg);
        vCodeCheck = false;
      }
    }
  })
});
$("#verify_").blur(function () {

  if (vCodeCheck == false) {
    regErr('验证码错误');
  }
});
var reg = {
  userAccount: /^[a-z0-9A-Z]{4,16}$/,
  pwd: /^[0-9a-zA-Z]{6,16}$/,
  VerifyCode: /^[0-9]{6}$/,
  relName: /^[\u4e00-\u9fa5]{2,16}$/,
  phone: /^1[34578]\d{9}$/,
  IDcard: /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|[Xx])$/
}
//注册事件
function register() {
  //invitationCode = $.trim( $('#invited').val() );
  if (invitationCode == '' || invitationCodeCheck == false) {
    //regErr('邀请码不能为空');
    return;
  }
  var userName = $.trim($('#userCode').val());
  if (userName == '') {
    regErr('账户不能为空');
    return;
  }
  if (!userName.match(reg.userAccount)) {
    regErr('账户为4-16字节字母或者数字组合');
    return;
  }
  var pwd1 = $.trim($('#userPwd').val());
  var pwd2 = $.trim($('#repetitived').val());
  if (pwd1 == '' || pwd2 == '') {
    regErr('密码不能为空');
    return;
  } else if (pwd1 != pwd2) {
    regErr('两次输入的密码不一致');
    return;
  } else if (!pwd1.match(reg.pwd)) {
    regErr('密码格式为6-16位数字或者字母组合(大、小写)');
    return;
  }
  var relName = $.trim($('.relName>input').val());
  if (relName == '') {
    regErr('真实姓名不能为空');
    return;
  } else if (!relName.match(reg.relName)) {
    regErr('请输入中文真实姓名，2-16个汉字');
    return;
  }
  var IDcard = $.trim($('.IDcard>input').val());
  if (relName == '') {
    regErr('身份证号不能为空');
    return;
  } else if (!IDcard.match(reg.IDcard)) {
    regErr('请输入身份证号码，15位或者18位');
    return;
  }
  var phone = $.trim($('.phone>input').val());
  if (phone == '') {
    regErr('手机号不能为空');
    return;
  } else if (!phone.match(reg.phone)) {
    regErr('手机号为11位阿拉伯数字');
    return;
  }

  var verifyCode = $.trim($('#verify_').val());
  if (verifyCode == '') {
    regErr('验证码不能为空');
    return;
  } else if (!verifyCode.match(reg.VerifyCode)) {
    regErr('验证码格式为6位数字');
    return;
  }
  if (vCodeCheck) {
    regHide();
    //传递注册后自动登陆数据
    var data = {
      'userCode': userName,
      'userPassword': $.md5(pwd1),
      'userConfirmPassword': $.md5(pwd2),
      'userName': relName,
      'userCardNo': IDcard,
      'userPhone': phone,
      'verify': verifyCode,
      'refer': invitationCode,
      'terminalType': 3
    };
    //请求接口
    $.ajax({
      async: false,
      type: 'post',
      url: "/user/registerAndloginUser",
      dataType: 'json',
      data: data,
      success: function (json) {
        if (json.retCode == '1') {
          regHide();
          alert('注册成功！');
          location.href = 'login.html';
        } else {
          regErr(json.retMsg);
        }
      }
    })
  }
}
//字段截取
function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

//reg error
function regErr(text) {
  $('.caution').removeClass('vis').find('span.errorMsg').html(text);
}
function regHide() {
  $('.caution').addClass('vis');
}

function SetCookie(name, second) {
  var exp = new Date();
  exp.setTime(exp.getTime() + second * 1000);
  document.cookie = name + "=" + escape(second);
}
function getCookie(name) {
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if (arr = document.cookie.match(reg))
    return unescape(arr[2]);
  else
    return null;
}
